package com.yubest.demo.exception;

import com.yubest.demo.dto.Response;
import com.yubest.demo.dto.ResponseSign;
import com.yubest.demo.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: GlobalControllerExceptionHandler
 * @Description:全局异常处理器
 */
@ControllerAdvice
@Slf4j
public class GlobalControllerExceptionHandler {



    //region 拦截捕捉自定义异常
    /**
     * 接口签名异常
     */
    @ExceptionHandler(SignServiceException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseSign handleServiceException(SignServiceException ex) {
        log.error(ex.getMessage(), ex);
        ResponseSign rs = new ResponseSign();
        rs.setCode(500);
        rs.setMessage(ex.getMessage());
        return rs;
    }
    //endregion







    //region 全局异常捕捉处理
    /**
     * 全局异常捕捉处理
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址:{},发生系统异常。", requestURI, e);
        return Response.error(e.getMessage());
    }


    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleRuntimeException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址:{},发生运行时异常。", requestURI, e);
        return Response.error(e.getMessage());
    }
    //endregion




    //region 异步处理方法
    /**
     * 异步处理方法
     * @param e
     */
    @Async
    public void sendMessage(Exception e) {
        //doing
    }
    //endregion


}
